from jose import JWTError, ExpiredSignatureError
from fastapi import Request, HTTPException, status

from handle.handle_log import log
from server.core.security import verify_token



def check_token(request):
    """
    检查 Token 的有效性：
    - 成功时返回 payload
    - 失败时返回 {"code": ..., "msg": ...}，并记录详细错误到日志
    """
    token = request.headers.get("JWT-Token")

    # 1. 检查 Token 是否存在
    if not token:
        log.error("Token 缺失: 请求头未提供 JWT-Token")
        raise  HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail={"code": 1401, "msg": "未提供 Token"},
        )
        # return {"code": 1401, "msg": "未提供 Token"}

    # 2. 验证 Token
    try:
        user_id = verify_token(token).get("id")
        return user_id  # 验证成功，返回 payload
    except ExpiredSignatureError as e:
        log.error(f"Token 已过期: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail={"code": 1401, "msg": "Token 已过期"},
        )
        #return {"code": 1401, "msg": "Token 已过期"}
    except JWTError as e:
        log.error(f"Token 验证失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail={"code": 1401, "msg": "无效 Token"},
        )
        #return {"code": 1401, "msg": "无效 Token"}
    except Exception as e:
        log.error(f"Token 验证异常: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail={"code": 1500, "msg": "无效 Token"},
        )
        #return {"code": 1500, "msg": "Token 验证错误"}




def get_current_user(request: Request):
    # 1. 验证Token
    current_user = check_token(request)
    # 如果返回的是字典，说明验证失败
    if isinstance(current_user, dict):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=current_user["msg"],
            headers={"WWW-Authenticate": "Bearer"},
        )

    # 验证成功，可以继续查询用户信息
    user_id = current_user[0]
    return user_id